﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Data;
using Commons;
using Dx.SqlAccess;

namespace ERMap
{
    public class ERMapHelper
    {
        /// <summary>
        /// 简单处理模型的获取和保存功能，hashtable的key一定要使用小写
        /// </summary>
        /// <param name="tablename"></param>
        /// <param name="keys"></param>
        /// <returns></returns>
        public static Hashtable getmodel(string tablename, Hashtable keys)
        {
            DataSet ds = getdata(tablename, keys);
            return DataUtil.DataRow2Hashtable(ds);
        }

        public static DataSet getdata(string tablename, Hashtable keys)
        {
            if (keys == null) throw new Exception("key不允许为空");

            StringBuilder sqlcmd = new StringBuilder();
            sqlcmd.AppendFormat("select * from {0} where isnull(isdel,0) = 0 ", tablename);

            foreach (DictionaryEntry key in keys)
            {
                sqlcmd.AppendFormat(" and {0} = @{0} ", key.Key);
            }

            ParameterCollection param = SqlDataAccess.Hash2Param(keys);

            return SqlDataAccess.GetDataSet(SqlDataAccess.SQLConnString1, CommandType.Text, sqlcmd.ToString(), param);
        }

        public static DataSet getCustomData(string sql, Hashtable param)
        {
            ParameterCollection args = SqlDataAccess.Hash2Param(param);
            DataSet ds = SqlDataAccess.GetDataSet(SqlDataAccess.SQLConnString1, CommandType.Text, sql, args);
            StringBuilder filter = new StringBuilder();
            if (Commons.DataUtil.IsValidate(ds))
            {
                foreach (DataColumn column in ds.Tables[0].Columns)
                {
                    Regex regex = new Regex(@"isdel/d*");
                    if (regex.IsMatch(column.ColumnName))
                    {
                        if (filter.Length > 0)
                            filter.Append(" and ");
                        filter.AppendFormat(" isnull({0},0) = 0 ", column.ColumnName);
                    }
                }
            }
            Commons.DataUtil.DataFilter(ds, filter.ToString(), "");
            return ds;
        }

        public static Hashtable getCustomModel(string sql, Hashtable param)
        {
            DataSet ds = getCustomData(sql, param);
            return DataUtil.DataRow2Hashtable(ds);
        }

        public static void setmodel(string tablename, string keyname, Hashtable data)
        {
            if (string.IsNullOrEmpty(keyname)) throw new Exception("key不允许为空");

            string[] keys = keyname.Split(new char[] { ',' });

            if (keys.Length == 0) throw new Exception("key不允许为空");

            Hashtable hkey = new Hashtable();
            foreach (string key in keys)
            {
                if (!data.Contains(key.ToLower())) throw new Exception("没有找到key值");
                hkey.Add(key, data[key.ToLower()]);
            }

            DataSet ds = getdata(tablename, hkey);

            DataRow row = null;

            if (!DataUtil.IsValidate(ds))//插入
            {
                row = ds.Tables[0].NewRow();
                ds.Tables[0].Rows.Add(row);
            }
            else //更新
            {
                row = ds.Tables[0].Rows[0];
            }
            DataUtil.Hashtable2DataRow(row, data, false, false, true);

            SqlDataAccess.ApplyData(tablename, ds.Tables[0].GetChanges());
        }

        public static void delmodel(string tablename, Hashtable keys)
        {
            string keyname = string.Empty;

            foreach (var key in keys.Keys)
            {
                if (!string.IsNullOrEmpty(keyname))
                    keyname += ",";
                keyname += Commons.StrUtil.FormatValue(key);
            }

            Hashtable model = getmodel(tablename, keys);
            if (model == null) return;
            model["isdel"] = "1";
            setmodel(tablename, keyname, model);
        }

        public static void destroy(string tablename, Hashtable keys)
        {
            string keyname = string.Empty;

            foreach (var key in keys.Keys)
            {
                if (!string.IsNullOrEmpty(keyname))
                    keyname += ",";
                keyname += Commons.StrUtil.FormatValue(key);
            }

            DataSet ds = getdata(tablename, keys);

            if (!Commons.DataUtil.IsValidate(ds)) return;

            foreach (DataRow row in ds.Tables[0].Rows)
            {
                row.Delete();
            }

            SqlDataAccess.ApplyData(tablename, ds.Tables[0].GetChanges());
        }

        public static string maxid(string tablename, string keyname)
        {
            StringBuilder sqlcmd = new StringBuilder();
            sqlcmd.AppendFormat("select max({1}) as m from {0} ", tablename, keyname);
            Hashtable max = getCustomModel(sqlcmd.ToString(), null);
            return Commons.StrUtil.FormatValue(max["m"]);
        }
    }
}
